package com.party.mobile.web.controller.crowdfund;

import com.google.common.collect.Lists;
import com.party.authorization.annotation.Authorization;
import com.party.common.paging.Page;
import com.party.common.utils.StringUtils;
import com.party.core.model.activity.Activity;
import com.party.core.model.crowdfund.Project;
import com.party.core.model.crowdfund.ProjectComment;
import com.party.core.model.crowdfund.Support;
import com.party.core.model.crowdfund.TargetProject;
import com.party.core.model.member.Member;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.crowdfund.IProjectCommentService;
import com.party.core.service.crowdfund.IProjectService;
import com.party.core.service.crowdfund.ISupportService;
import com.party.core.service.crowdfund.ITargetProjectService;
import com.party.core.service.member.IMemberService;
import com.party.core.service.system.ISysConfigService;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.login.output.CurrentUser;
import com.party.notify.notifyPush.servce.INotifySendService;
import com.vdurmont.emoji.EmojiParser;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 众筹评论控制器
 * Created by Juliana
 *
 * @date 2017/3/1 0001
 * @time 10:17
 */

@Controller
@RequestMapping(value = "/crowdfund/pcomment")
public class ProjectCommentController {

    private static Logger logger = LoggerFactory.getLogger(ProjectCommentController.class);

    @Autowired
    private IProjectCommentService projectCommentService;
    @Autowired
    private CurrentUserBizService currentUserBizService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private INotifySendService notifySendService;
    @Autowired
    private ISupportService supportService;
    @Autowired
    private ITargetProjectService targetProjectService;
    @Autowired
    private IActivityService activityService;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private ISysConfigService sysConfigService;

    /**
     * 获取当前用户的众筹目标
     * @param request 请求参数
     * @return 交互数据
     */
    @Authorization
    @ResponseBody
    @RequestMapping(value = "replyComment")
    public AjaxResult replyComment(ProjectComment comment ,HttpServletRequest request){
        AjaxResult ajaxResult = new AjaxResult();
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        comment.setCreateBy(currentUser.getId());
        if ("undefined".equals(comment.getReplyId())) {
            comment.setReplyId(null);
        }
        boolean isConvertBase64 = sysConfigService.isConvertBase64();
        String commentStr = comment.getComment();
        if (StringUtils.isNotEmpty(commentStr)) {
            if (isConvertBase64) {
                commentStr = StringUtils.encodeBase64(commentStr);
            } else {
                commentStr = EmojiParser.parseToAliases(commentStr);
            }
            comment.setComment(commentStr);
        }
        String id = projectCommentService.insert(comment);

        try {
            Support support = supportService.get(comment.getRefId());
            Project project = projectService.get(support.getProjectId());
            TargetProject targetProject = targetProjectService.findByProjectId(support.getProjectId());
            Activity activity = activityService.get(targetProject.getTargetId());
            ProjectComment projectComment = projectCommentService.get(id);
            Member proMember = memberService.get(project.getAuthorId());
            Member author = memberService.get(support.getFavorerId());
            String commentName;
            String authorId;
            if (StringUtils.isEmpty(projectComment.getReplyId())) {
                commentName = proMember.getRealname();
                authorId = author.getId();
            } else {
                commentName = author.getRealname();
                authorId = proMember.getId();
            }
            commentStr = projectComment.getComment();
            if (StringUtils.isNotEmpty(commentStr)) {
                if (isConvertBase64) {
                    commentStr = StringUtils.decodeBase64New(commentStr);
                } else {
                    commentStr = EmojiParser.parseToUnicode(commentStr);
                }
                projectComment.setComment(commentStr);
            }
            notifySendService.sendAcceptCrowfundComment(commentName, projectComment.getComment(), authorId,
                    activity.getMember(), support.getProjectId());
        } catch (Exception e) {
            logger.error("发送微信模板消息(收到众筹回复)异常", e);
        }
        ajaxResult.setSuccess(true);
        ajaxResult.setData(id);
        return ajaxResult;
    }

    /**
     * 获取评论分页数据
     * @param comment
     * @param page
     * @return
     */
    @ResponseBody
    @RequestMapping("replyCommentPage")
    public AjaxResult replyCommentPage(ProjectComment comment, Page page) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            boolean isConvertBase64 = sysConfigService.isConvertBase64();
            int pageNo = page.getPage();
            int pageSize = page.getLimit();
            List<Map<String, String>> parents = projectCommentService.findParentComments(comment.getRefId());
            List<Map<String, String>> result = Lists.newArrayList();
            int start = (pageNo - 1) * pageSize;
            int end = pageNo * pageSize;
            if (CollectionUtils.isNotEmpty(parents)) {
                parents.forEach(map -> {
                    String commentStr = map.get("comment");
                    if (StringUtils.isNotEmpty(commentStr)) {
                        if (isConvertBase64) {
                            commentStr = StringUtils.decodeBase64New(commentStr);
                        } else {
                            commentStr = EmojiParser.parseToUnicode(commentStr);
                        }
                        map.remove("comment");
                        map.put("comment", commentStr);
                    }
                    List<Map<String, String>> children = projectCommentService.findChildrenComments(map.get("id"));
                    if (CollectionUtils.isNotEmpty(children)) {
                        map.put("isReply", "1");
                        map.put("isCrowdfunder", "1");
                        result.add(map);
                        Map<String, String> child = children.get(0);
                        child.put("isCrowdfunder", "0");
                        String commentStrChild = child.get("comment");
                        if (StringUtils.isNotEmpty(commentStrChild)) {
                            if (isConvertBase64) {
                                commentStrChild = StringUtils.decodeBase64New(commentStrChild);
                            } else {
                                commentStrChild = EmojiParser.parseToUnicode(commentStrChild);
                            }
                            child.remove("comment");
                            child.put("comment", commentStrChild);
                        }
                        result.add(child);
                    } else {
                        map.put("isReply", "0");
                        map.put("isCrowdfunder", "1");
                        result.add(map);
                    }
                });
            }
            int size = result.size();
            start = start > size ? size : start;
            end = end > size ? size : end;
            List<Map<String, String>> r = result.subList(start, end);
            ajaxResult.setSuccess(true);
            ajaxResult.setData(r);
            return ajaxResult;
        } catch (Exception e) {
            logger.error("众筹支持评论加载分页异常", e);
        }
        ajaxResult.setSuccess(false);
        return ajaxResult;
    }
}
